package com.wzq.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lmax.disruptor.util.Util;
import com.wzq.bean.DataCollectionModel;
import com.wzq.bean.Result;
import com.wzq.bean.UserModel;
import com.wzq.service.DataCollectionService;
import com.wzq.service.UserService;
import com.wzq.util.ApiException;
import com.wzq.util.ApiResponse;
import com.wzq.util.ResponseCode;
import com.wzq.util.UploadPicUtil;
import com.wzq.util.UtilDate;
import com.wzq.util.UtilString;


@Controller
@RequestMapping("uploadfile/")
public class UploadController {
	
         private Result result=new Result(); 
      	@Value("${app.api.path}")
    	private String path;
         @Autowired
         private DataCollectionService dataCollectionService;
     	@Autowired
    	private UserService userService;
         @RequestMapping("upload")  
         @ResponseBody      //把回传类转换成json  
         public  Result uploadPhone(@RequestParam(value="file",required=false)MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{  
                   String path=uploadFile(file, request);  
                   result.setCode("200");  
                   result.setPath(path);  
                   result.setMessage("上传成功");  
                //   new myThThread().start();
                   return result;  
  
         }  
         @RequestMapping(value ="uploadPhoneData",method=RequestMethod.POST)  
         @ResponseBody      //把回传类转换成json  
         public  Result uploadPhoneData(DataCollectionModel model,HttpServletRequest request) throws IllegalStateException, IOException{  
        	
        	UserModel user = new UserModel();
        	user = userService.getByAccount(model.getUsername());
        	 if(null!=model){
                boolean u=user.getName().equals(model.getUsername()) ;
        		boolean p=user.getPassword().equals(UtilString.md5(model.getPassword()));
        		 if ( u && p) {
        			System.out.println(model.getCollectionType()+"!!!!!");
             		System.out.println(model.getRegion()+"~~~~~~");
             		Date d=UtilDate.StringToDate(model.getCollectTimeStr());
             		model.setCollectTime(d);
             		model.setInsertTime(new Date());
             		
             		if(null!=model.getPicture1()&&!"".equals(model.getPicture1())){
             			UploadPicUtil.uploadPic(model.getPicture1(), model.getPictureName1(),path);
             		}
             		if(null!=model.getPicture2()&&!"".equals(model.getPicture2())){
             			UploadPicUtil.uploadPic(model.getPicture2(), model.getPictureName2(), path);
             		}
             		if(null!=model.getPicture3()&&!"".equals(model.getPicture3())){
             			UploadPicUtil.uploadPic(model.getPicture3(), model.getPictureName3(), path);
     				}
             		model.setPicture1("");
             		model.setPicture2("");
             		model.setPicture3("");
             		dataCollectionService.add(model);
             		result.setCode("200");  
        	    	result.setPath(null);  
        	    	result.setMessage("上传成功"); 
        		 }else{
        			 result.setCode("300");  
        	    	 result.setPath(null);  
             	     result.setMessage("无效用户，上传失败！");
        		}
        		
        	}else{
        		 result.setCode("300");  
         	     result.setPath(null);  
         	     result.setMessage("数据上传失败");
        	}
    	   /* result.setCode("200");  
    	    result.setPath(null);  
    	    result.setMessage("上传成功");  */
           return result;  
         }  
         
       /*  @RequestMapping(value ="uploadPhoneData",method = RequestMethod.POST)  
     	@ResponseBody
    	public Result uploadPhoneData(DataCollectionModel dto, String password,HttpSession httpSession)throws ApiException{
    		
    			System.out.println(dto.getCollectionType());
    			result.setCode("200");  
	    	    result.setPath(null);  
	    	    result.setMessage("上传成功"); 
    		return result;
    	}*/
         /** 
          * 上传 
          * @param file 
          * @param request 
          * @return 
          * @throws IOException 
          */  
         private String  uploadFile(MultipartFile file,HttpServletRequest request)  
                            throws IOException {  
                   String fileName=file.getOriginalFilename();  
                   File targetFile=new File(path,fileName);  
                   if(!targetFile.exists()){  
                      targetFile.mkdirs();  
                   }  
                   file.transferTo(targetFile);  
         //  request.setAttribute("filePath",targetFile.getAbsolutePath());  
                   return    targetFile.getAbsolutePath();  
  
         }  
 class myThThread extends Thread{
	 @Override
	public void run() {
		super.run();
		System.out.println("录入数据线程开始.....");
		 String FILE_IN = "E:\\myImage";
	    File f = new File(FILE_IN);
	    List<String> list = new ArrayList<String>();
	    list = getFileList(f);
	    String text=null;

	    System.out.println(list.size());

	    for (String l : list) {

	   try {
		text=getTextFromTxt(l);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	   System.out.println(text.toString());
		
	}
	 
 }
 public  List<String> getFileList(File file) {

	    List<String> result = new ArrayList<String>();

	    if (!file.isDirectory()) {
	        //System.out.println(file.getAbsolutePath());
	        result.add(file.getAbsolutePath());
	    } else {
	        File[] directoryList = file.listFiles(new FileFilter() {
	            public boolean accept(File file) {
	                if (file.isFile() && file.getName().indexOf("txt") > -1) {
	                    return true;
	                } else {
	                    return false;
	                }
	            }
	        });
	        for (int i = 0; i < directoryList.length; i++) {
	            result.add(directoryList[i].getPath());
	        }
	    }

	    return result;
	}
		public  String getTextFromTxt(String filePath) throws Exception {   
	
		    FileReader fr = new FileReader(filePath);   
		    BufferedReader br = new BufferedReader(fr);   
		    StringBuffer buff = new StringBuffer();   
		    String temp = null;   
		    while ((temp = br.readLine()) != null) {   
		        buff.append(temp + "\r\n");   
		    }   
		    br.close();   
		    return buff.toString();   
		} 
	 }
 
 
}
